please explain this program line by line mainly i do not understand what happened in the second line

by: karuppaiya, 7 years ago


def test(n):
    if n & 1 :
        print('The is  odd number ',n)
    else:
        print('This is even number :',n)
test(25)



You must be logged in to post. Please login or register an account.



hi,
2nd row means if number n (binary AND ) 1 gives on output 1
for example; if u have number 1 which is binary 0000 0001 and on this you & with number 1
(binary AND gives 1 on output only if both of same bits (on same position) in one byte are 1)
so
0000 0001 &
0000 0001
-------------------
0000 0001 -> output will be true cause both bits on 1st position must be 1 because
                         number one have 1 only in 1st bit)

number 2 DEC
is 0000 0010 &    (and if u & number 2 with 1)
    0000 0001
--------------------------
    0000 0000 -> so output is 0

number 3 DEC

0000 0011 &
0000 0001
------------------
0000 0001 -> gives 1

and so on..

so any number you use, if first bit of this number(from right to left) is 1, output will be 1 (or true), and for your example, every number which have 1 as first bit is odd number

in first line you define method (test) which pass parameter (n) to the condition (if) which is checked in 2nd line I explain above, so if answer is true, program will print first condition and if not true output will be 2nd print.

in last line u pass any number you want to the method.
your number 25 DEC is 0001 1001 BIN

0001 1001 &
0000 0001
____________
0000 0001 so number 25 is odd number!

hope this helps :)


one more explanation:
if you want & with number which have 1 on two bits (e.g.  number 6(DEC) is 0000 0110(BIN)

54 & 6
54 -> 0011 0110 &
6   -> 0000 0110
____________________
          0000 0110 -> both of bits on 2nd and 3rd position in number 54 are 1 so output is true or number 6 (always will be number u use after & operand if condition is true)

-bradarius1 7 years ago
Last edited 7 years ago

You must be logged in to post. Please login or register an account.